<template>
  <div class="send-medici-container">
    <!-- 顶部区域 -->
	<!-- 悬浮按钮 -->
	<div v-if="isMinimized" class="minimized-button" @click="restoreDialog">
	  <i class="el-icon-message"></i>
	</div>
    <div class="send-medici-header">
		<i class="el-icon-zyf" style="border-radius: 50%;font-size: 20px;padding: 6px;margin-left: 8px;;background-color: #ff0000;color: #fff;"></i>
		<h4 style="margin-left: 12px;">中药房退药</h4>
		<!-- 在顶部搜索区域添加状态筛选 -->
		<div class="filter-section">
		  <!-- <span style="font-size: 12px;color: #606266;font-weight: bold;display: inline-block;width: 68px;">状态筛选：</span> -->
		  <el-select
		    v-model="filterState"
		    placeholder="请选择状态"
		    size="mini"
		    clearable
		    @change="handleStateFilterChange"
		    style="width: 180px;"
		  >
		    <el-option
		      v-for="(label, value) in statusMap"
		      :key="value"
		      :label="label"
		      :value="value"
		    ></el-option>
		  </el-select>
		</div>
		<!-- btn2 -->
		<div class="main-icon-c">
			<span style="font-size: 12px;color: #606266;font-weight: bold;display: inline-block;width: 88px;">单据编号：</span>
			<el-input size="mini" placeholder="编号、姓名、拼音简码" suffix-icon="el-icon-Ssearch" v-model="searchValue"></el-input>
		</div>
		
		<!-- 时间日期筛选条件 -->
		<div class="datePicker">
		  <span style="font-size: 12px;color: #606266;font-weight: bold;display: inline-block;width: 68px;">开始时间：</span>
		  <el-date-picker
		    v-model="startDate"
		    type="datetime"
		    placeholder="选择开始时间"
		    size="mini"
		    value-format="yyyy-MM-dd HH:mm:ss"
		    :picker-options="startDatePickerOptions"
		    style="width: 180px;"
		  ></el-date-picker>
		  
		  <span style="font-size: 12px;color: #606266;font-weight: bold;display: inline-block;width: 68px;margin-left: 12px;">结束时间：</span>
		  <el-date-picker
		    v-model="endDate"
		    type="datetime"
		    placeholder="选择结束时间"
		    size="mini"
		    value-format="yyyy-MM-dd HH:mm:ss"
		    :picker-options="endDatePickerOptions"
		    style="width: 180px;"
		  ></el-date-picker>
		</div>
		
		<!-- btn3 -->
		<div class="main-icon-c">
			<!-- 查询按钮 -->
			<el-button size="mini" :loading="loading" type="info" @click="found" icon="el-icon-Ssearch">查询</el-button>
			<el-button v-for="(v,i) in headerBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini" @click="handClick(v,i)">{{ v.title }}</el-button>
		</div>
    </div>
    
    <!-- 主体区域 -->
    <div class="send-medici-main" ref='myBox' v-if="!isMinimized">
		<div class="table">
			<el-table :data="tableData" border highlight-current-row :max-height="tableHeight" :row-class-name="getRowClass"
			element-loading-text="数据加载中..." v-loading="loading" element-loading-spinner="el-icon-loading"
			@current-change="handleCurrentTableChange">
				<el-table-column prop="phayId" label="药房名称" align="center">
					<template slot-scope="{ row }">
						<!-- 根据state显示 -->
						<span>{{ shedIdMap[row.phayId] || '未知库房' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="status" label="状态" align="center">
					<template slot-scope="{ row }">
						<!-- 根据state显示不同的图标 -->
						<i :class="statusIconMap[row.state]" :style="{ color: statusColorMap[row.state] }"></i>
						<span>{{ statusMap[row.state] || '未知状态' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="rxNo" label="处方编号" width="168" align="center"></el-table-column>
				<el-table-column prop="name" label="病人姓名" align="center"></el-table-column>

				<el-table-column prop="sex" sortable label="性别" width="80" align="center">
				  <template slot-scope="scope">
				    <span>
				      <i :class="scope.row.sex === 1 ? 'el-icon-male' : 'el-icon-female'" 
				          :style="{color: scope.row.sex === 1 ? '#000039' : '#F56C6C'}"></i>
				      {{ scope.row.sex === 1 ? '男' : '女' }}
				    </span>
				  </template>
				</el-table-column>
				<el-table-column prop="age" label="年龄" align="center"></el-table-column>
				<el-table-column prop="pricingType" label="划价方式" width="128" align="center">
					<template slot-scope="{ row }">
						<!-- 根据state显示不同的图标 -->
						<span>{{ pricingTypeMap[row.pricingType] || '未知' }}</span>
					</template>
				</el-table-column>
				<el-table-column v-for="(col, inx) in tableRows" :key="inx" 
				:type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column>
				<!-- fixed -->
				<el-table-column fixed="left" label="行号" type="index"></el-table-column>
				<!-- edit -->
				<!-- <el-table-column fixed="right" label="操作" width="88">
					  <template slot-scope="scope">
						<div class="editbox" style="text-align: center;">
							<el-link type="info" size="mini">修改</el-link>
							<el-link type="danger" size="mini">删除</el-link>
						</div>
					  </template>
				</el-table-column> -->
			</el-table>
		</div>
    </div>
    
    <!-- 底部区域 (100%宽度) -->
    <div class="send-medici-bottom">
      <div class="bottom-left">
<!-- 		<el-button disabled type="primary" size="small">全选</el-button>
		<el-button disabled type="primary" size="small">全不选</el-button>
		<el-button disabled type="primary" size="small">选择可退</el-button> -->
		<!-- <el-button type="success" size="small">预览</el-button> -->
		<!-- <el-button type="warning" size="small">打印</el-button> -->
		<!-- <el-checkbox v-model="closeAfterPrint" style="margin-left: 10px;">自动打印</el-checkbox> -->
<!-- 		
        <el-button type="primary" size="small">设置打印机</el-button>
        <el-button type="primary" size="small">本地格式属性</el-button>
        <el-checkbox v-model="closeAfterPrint" style="margin-left: 10px;">打印后关闭此窗口</el-checkbox> -->
		<!-- 分页 -->
		<el-pagination
		style="margin: 12px;"
		@size-change="handleSizeChange"
		@current-change="handleCurrentChange"
		:current-page="pageNum"
		:page-sizes="[20, 50, 100]"
		:page-size="pageSize"
		:total="totalSize"
		layout="total, sizes, prev, pager, next, jumper"
		background
		>
		</el-pagination>
      </div>
      <!-- 底部区域 (100%宽度) -->
        <div class="send-medici-bottom">
          <div class="bottom-right">
            <el-checkbox disabled v-model="closeAfterPrint" style="margin-left: 10px;">自动打印</el-checkbox>
            <el-checkbox disabled v-model="showDatas" style="margin-right: 12px;">显示明细</el-checkbox>
            <!-- 退费 -->
         <!--   <el-button 
              type="danger" 
			  size="mini"
              :disabled="!isRefundAllowed"
              @click="handleRefundPrice"
            > 退费  </el-button> -->
            <!-- 退药 -->
            <el-button 
              type="warning" 
			  size="mini"
              :disabled="!isDrugRefundAllowed"
              @click="handleRefund"
            > 退药 </el-button>
            <!-- 打印 -->
            <el-button 
              type="primary" 
			  size="mini"
              :disabled="!isOtherActionAllowed"
            > 打印 </el-button>
            <el-button 
              type="primary" 
              size="small" 
              @click="handleView"
              :disabled="!isOtherActionAllowed"
            >
              查看
            </el-button>
            <!-- 修改删除按钮，添加点击事件 -->
			<el-button 
				type="danger" 
				size="small" 
				:disabled="!isOtherActionAllowed"
				@click="handleDelete"
			>删除</el-button>
            <el-button type="info" size="small">关闭</el-button>
          </div>
      </div>
	  <!-- 新增详情模态框 -->
	    <el-dialog
	      title="处方详情"
	      :visible.sync="detailDialogVisible"
	      width="68%"
	      top="5vh"
	      custom-class="detail-dialog"
	      :before-close="handleCloseDetailDialog">
	      
	      <!-- 顶部表单区域 -->
	       <!-- 修改顶部表单区域 -->
	       <el-card class="form-card" shadow="hover">
	         <el-descriptions
	           :title="detailForm.pharmacyName"
	           border
	           :column="3"
	           size="small"
	           class="form-descriptions"
	         >
	           <!-- 第一行 -->
	           <el-descriptions-item label="患者姓名">
	             <el-tag size="small">{{ detailForm.name || '-' }}</el-tag>
	           </el-descriptions-item>
	           <el-descriptions-item label="健康ID">
	             <el-tag size="small">{{ detailForm.patientId || '-' }}</el-tag>
	           </el-descriptions-item>
	           <el-descriptions-item label="年龄">
	             <el-tag size="small">{{ detailForm.age || '-' }}</el-tag>
	           </el-descriptions-item>
	       
	           <!-- 第二行 -->
	           <el-descriptions-item label="处方类型">
	             <el-tag size="small" type="info">{{ detailForm.rxName || '-' }}</el-tag>
	           </el-descriptions-item>
<!-- 	           <el-descriptions-item label="病人类型">
	             <el-tag size="small" type="info">{{ detailForm.patientName || '-' }}</el-tag>
	           </el-descriptions-item> -->
	       
	           <!-- 第三行 -->
	           <el-descriptions-item label="处方编号">
	             <el-tag size="small" type="warning">{{ detailForm.rxNo || '-' }}</el-tag>
	           </el-descriptions-item>
	           <el-descriptions-item label="性别">
				   <el-tag>
				     <i :class="detailForm.sex === 1 ? 'el-icon-male' : 'el-icon-female'" 
				   	  :style="{color: detailForm.sex === 1 ? '#000039' : '#F56C6C'}"></i>
				     {{ detailForm.sex === 1 ? '男' : '女' }}
				   </el-tag>
	             <!-- <el-tag size="small" type="warning">{{ detailForm.sex || '-' }}</el-tag> -->
	           </el-descriptions-item>
	           <el-descriptions-item label="处方金额">
	             <el-tag size="small" type="danger">{{ detailForm.saleAmt || '0.00' }}</el-tag>
	           </el-descriptions-item>
	       
	           <!-- 第四行 -->
	           <el-descriptions-item label="处方医生" :span="1">
	             <el-tag size="small">{{ detailForm.bilgDrName || '-' }}</el-tag>
	           </el-descriptions-item>
	           <el-descriptions-item label="处方科室" :span="2">
	             <el-tag size="small">{{ detailForm.bilgDeptName || '-' }}</el-tag>
	           </el-descriptions-item>
				<el-descriptions-item label="中药用法" :span="3">
				  <el-tag size="small">{{ detailForm.tcmWayName || '-' }}</el-tag>
				</el-descriptions-item>
	           <!-- 第五行 -->
	           <el-descriptions-item label="中医诊断" :span="3">
	             <el-tag size="small">{{ detailForm.icdName || '-' }}</el-tag>
	           </el-descriptions-item>
	       
	           <!-- 第六行 -->
	           <el-descriptions-item label="处方备注" :span="3">
	             <el-tag size="small" type="info">{{ detailForm.remark || '-' }}</el-tag>
	           </el-descriptions-item>
	         </el-descriptions>
	       </el-card>
	      
	      <!-- 底部表格区域 -->
	      <el-card class="table-card">
	        <el-table
	          :data="detailMedicineList"
	          border
	          style="width: 100%"
	          class="prescription-table">
	          <el-table-column type="index" label="行号" width="50"></el-table-column>
	          <el-table-column prop="code" label="编码" width="128" ></el-table-column>
	          <el-table-column prop="name" label="药品名称" width="180"></el-table-column>
	          <el-table-column prop="drugSpec" label="规格描述" width="150"></el-table-column>
	          <el-table-column prop="medcWayName" label="给药方式" width="100" >
<!-- 				<template slot-scope="{ row }">
					<span>{{ TypeMap[row.medcWayId] || '' }}</span>
				</template> -->
			  </el-table-column>
	          <el-table-column prop="prodentpName" label="生产厂家" width="200"></el-table-column>
	          <el-table-column prop="cnt" label="数量" width="80" >
	            <template slot-scope="scope">
	              <span class="red-text">{{ scope.row.cnt + scope.row.unt }}</span>
	            </template>
	          </el-table-column>
	          <el-table-column prop="pacCnt" label="包装数量" width="80" ></el-table-column>
	          <el-table-column prop="salePric" label="零售单价" width="100"></el-table-column>
	          <el-table-column prop="saleAmt" label="零售金额" width="100">
	            <template slot-scope="scope">
	              <span class="red-text">{{ scope.row.saleAmt }}</span>
	            </template>
	          </el-table-column>
<!-- 	          <el-table-column prop="sdoseSum" label="用药剂量(总剂量)" width="100" align="center">
				  <template slot-scope="scope">
				    <span class="red-text">{{ scope.row.sdoseCnt * scope.row.prdCnt * scope.row.prdDays }}</span>
				  </template>
			  </el-table-column> -->
	          <!-- <el-table-column prop="sdoseUnt" label="剂量单位" width="100" align="center"></el-table-column> -->
	        </el-table>
	        
	        <!-- 底部操作按钮 -->
	        <div class="action-buttons">
				<el-button type="primary" size="small" @click="gotoPrint">打印处方</el-button>                        
				<el-button type="primary" size="small" @click="detailDialogVisible = false">关闭</el-button>
	        </div>
	      </el-card>
	    </el-dialog>
	  <!-- 在模板底部添加退药模态框 -->
	  <!-- 退药模态框 -->
	    <el-dialog 
	      title="[中药房] - 门诊处方退药" 
	      :visible.sync="refundDialogVisible" 
	      width="58%"
		  top="18px"
	      :before-close="handleCloseRefundDialog"
	      custom-class="refund-dialog">
	      
	      <!-- 顶部信息区域 -->
	      <!-- 顶部信息区域 - 修改后 -->
	      <div class="info-section">
	        <el-descriptions class="margin-top" :title=" '药房:' + addForm.bilgDeptName" :column="4" size="small" border>
	          <!-- 第一行 -->
	          <el-descriptions-item label="患者姓名">
	            <el-tag size="small">{{ addForm.name || '古老板' }}</el-tag>
	          </el-descriptions-item>
			  <el-descriptions-item label="性别">
			    <!-- <el-tag size="small">{{ addForm.sex === '1' ? '男' : '女' }}</el-tag> -->
				<span>
				  <i :class="addForm.sex === 1 ? 'el-icon-male' : 'el-icon-female'" 
					  :style="{color: addForm.sex === 1 ? '#000039' : '#F56C6C'}"></i>
				  {{ addForm.sex === 1 ? '男' : '女' }}
				</span>
			  </el-descriptions-item>
			  <el-descriptions-item label="年龄">
			    <el-tag size="small">{{ addForm.age + '岁' || '28岁' }}</el-tag>
			  </el-descriptions-item>
	          
	          
	          <!-- 第二行 -->
			  <el-descriptions-item label="处方编号">
			    <el-tag size="small">{{ addForm.rxNo || 'JZ000000001' }}</el-tag>
			  </el-descriptions-item>
			  <el-descriptions-item label="处方类别">
			    <el-tag size="small">{{ addForm.rxName || '急诊' }}</el-tag>
			  </el-descriptions-item>
	          <el-descriptions-item label="处方金额">
	            <el-tag size="small" type="danger">{{ addForm.saleAmt || '' }}</el-tag>
	          </el-descriptions-item>
	         	          
	          <!-- 第三行 -->
	          <el-descriptions-item label="处方科室">
	            <el-tag size="small">{{ addForm.bilgDeptName || '九阵门诊' }}</el-tag>
	          </el-descriptions-item>
	          <el-descriptions-item label="处方医生">
	            <el-tag size="small">{{ addForm.bilgDrName || '九阵管理员' }}</el-tag>
	          </el-descriptions-item>
			  <el-descriptions-item label="划价方式">
				<span>{{ pricingTypeMap[addForm.pricingType] || '' }}</span>
			  </el-descriptions-item>
			  <el-descriptions-item label="给药方式">
			    <el-tag size="small">{{ addForm.medcWayName || '' }}</el-tag>
			  </el-descriptions-item>
			  <el-descriptions-item label="处方诊断">
			    <el-tag size="small">{{ addForm.icdName || '' }}</el-tag>
			  </el-descriptions-item>
			   
	        </el-descriptions>
	        
	        <!-- 底部备注和退药原因区域 -->
	        <div style="margin-top: 12px;">
	          <el-row :gutter="24">
	            <el-col :span="12">
	              <el-descriptions :column="1" size="small">
					  <el-descriptions-item label="退药原因">
					    <el-select
					      v-model="addForm.refundReason"
					      placeholder="请选择退药原因"
					      size="mini"
					      filterable
					      allow-create
					      clearable
					      style="width: 100%"
					    >
					      <el-option
					        v-for="item in refundReasons"
					        :key="item.id"
					        :label="item.value"
					        :value="item.value"
					      ></el-option>
					    </el-select>
					  </el-descriptions-item>
	                
	              </el-descriptions>
	            </el-col>
	            <el-col :span="24">
	              <el-descriptions :column="1" size="small">
	                <el-descriptions-item label="备注说明">
	                  <el-input type="textarea" :rows="3" v-model="addForm.remark" placeholder="请输入备注" size="mini"></el-input>
	                </el-descriptions-item>
	              </el-descriptions>
	            </el-col>
	          </el-row>
	        </div>
	      </div>
	      
	      <!-- 药品表格区域 - 修改了数据绑定 -->
		    <el-table
		      :data="innerTableData"
		      border
		      ref="innerTable"
		      highlight-current-row
		      :max-height="tableHeight"
		      :row-class-name="getRowClass"
		      element-loading-text="数据加载中..."
		      v-loading="loading"
		      element-loading-spinner="el-icon-loading"
		    >
		    <!-- 添加多选框列 -->
		   <!-- <el-table-column
		      type="selection"
		      width="55"
		      align="center"
		    ></el-table-column> -->
			<el-table-column prop="code" label="编码" width="128"></el-table-column>
				<el-table-column prop="name" label="药品名称" width="88"></el-table-column>
				<el-table-column prop="drugSpec" label="规格描述" width="88"></el-table-column>
				<el-table-column prop="cnt" label="数量" width="68"></el-table-column>
				<el-table-column prop="unt" label="单位" width="68"></el-table-column>
				<el-table-column prop="salePric" label="零售单价" width="88"></el-table-column>
				<el-table-column prop="saleAmt" label="零售金额" width="88"></el-table-column>
				<el-table-column prop="retnCnt" label="待退数量" width="88" align="center">
				  <template slot-scope="scope">
				    <el-input
				      v-if="scope.$index === editingIndex"
				      v-model="scope.row.retnCnt"
				      size="mini"
				      @blur="handleEditBlur(scope.row, scope.$index)"
				      @keyup.enter.native="handleEditBlur(scope.row, scope.$index)"
				      ref="editInput"
				    ></el-input>
				    <span 
				      v-else
				      @dblclick="handleCellDblClick(scope.row, scope.$index)"
				      @click="handleCellClick(scope.row, scope.$index)"
				    >{{ scope.row.retnCnt }}</span>
				  </template>
				</el-table-column>
				<el-table-column prop="retnAmt" label="待退金额" width="88"></el-table-column>
				<el-table-column prop="returnedCnt" label="已退数量" width="88"></el-table-column>
				<el-table-column prop="returnedAmt" label="已退金额" width="88"></el-table-column>
				<el-table-column prop="prodentpName" label="生产厂家" width="128"></el-table-column>
<!-- 				<el-table-column prop="selfProe" label="自备药品" width="88"></el-table-column>
				<el-table-column prop="skintstDicm" label="皮试否" width="58"></el-table-column>
				<el-table-column prop="skintstRslt" label="皮试结果" width="88"></el-table-column> -->
				<el-table-column prop="minSalePric" label="小单位零售" width="88"></el-table-column>

		  	<!-- <el-table-column v-for="(col, inx) in tableRows2" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column> -->
		  	<!-- fixed -->
		  	<el-table-column fixed="left" label="行号" type="index" width="48" align="center"></el-table-column>
		  </el-table>
	     
	      
	      <!-- 底部操作区域 -->
	      <div class="footer-section">
	        <div class="total-amount">
	          <span class="amount-label">退药金额：</span>
	          <span class="amount-value">{{ formatCurrency(refundTotalAmount) }}</span>
	        </div>
	        <div class="action-buttons">
	          <el-button :loading="loading" size="small" @click="clearAll">清空</el-button>
	          <el-button :loading="loading" type="danger" size="small" plain @click="refundAll">全退</el-button>
	          <el-button :loading="loading" type="primary" size="small" plain @click="handleBatchRefund">确定</el-button>
	          <el-button size="small" @click="handleCloseRefundDialog">取消</el-button>
	        </div>
	      </div>
	    </el-dialog>
    </div>
	 <!-- 在父组件模板中添加子组件 -->
	  <refund-detail-dialog
	    :visible="refundDetailVisible"
	    :order-data="currentOrder"
	    @update:visible="val => refundDetailVisible = val"
	    @close="handleCloseRefundDetail"
	    @refund="handleConfirmRefund"
	  />
  </div>
</template>

<script>
// 接口
import { 
	tySave,rxmainPage,getRefundDrug,deltyrefund,
	getDrxExePlanInfo , // 查询处方是否有护理执行
} from "@/api/MedicenHouse/traMediciGive.js";
// props
// 引入子组件
import RefundDetailDialog from './RefundDetailDialog.vue'
// axios
import { getMedicationFrequency } from "@/api/MedicenCata.js";
// import { tyrefund,deltyrefund } from "@/api/MedicenHouse/traMediciGive.js";

// import { rxmainPage } from "@/api/MedicenHouse/traMediciGive.js";

export default {
	inject: ['reload'], // 无痕刷新
	components:{
		RefundDetailDialog
	},
	name: 'SendMedici',
	data() {
		return {
		  name:'',
		  WcId:'',
		  patientId:'',
		  searchValue:'',
		  tableHeight:'640',
		  pageNum: 1, //当前页currentPage
		  pageSize: 20,
		  totalSize: 0, //总条数
		  // 已有数据...
		  buttonsDisabled: false, // 控制所有按钮的禁用状态
		  selectedRows: [], // 添加这行
		  isMinimized: false,
		  refundDialogVisible: false, // 控制退药模态框显示
		  refundDrugList: [], // 退药详情列表
		  currentSelectedRow: null, // 当前选中的行数据
		  loading:false,
		  editingIndex: -1, // 当前正在编辑的行索引
		  // 新增数据属性
			detailDialogVisible: false,
			detailForm: {
			  pharmacyName: '',
			  rxName: '',
			  rxNo: '',
			  patientId: '',
			  name: '',
			  sex: '',
			  age: '',
			  patientType: '',
			  saleAmt: '',
			  bilgDrName: '',
			  bilgDeptName: '',
			  remark: '',
			  icdName: '',
			  tcmWayName:''
			},
			detailMedicineList: [],
		  form: {
			pharmacyName: '中药房(人民路)',
			dispensingWindow: '2号窗口(人民路)',
			windowStatus: '启用',
			patientId: '',
			prescriptionSearch: '',
			dispensingRange: '今日待发',
			refreshTime: '10',
			showBatch: true
      },
      rightForm: {
        prescriptionNumber: '',
        bilgDrName: '',
        patientId: '',
        gender: '',
        age: '',
        patientType: '',
        prescriptionDept: '',
        prescriptionDoctor: '',
        prescriptionAmount: '',
        prescriptionType: '',
        skinTest: '',
        agentName: '',
        agentId: '',
        westernDiagnosis: '',
        symptoms: '',
        allergyInfo: '',
        otherInfo: '',
        dispenser: '',
        dispensingWindow: '',
        remarks: ''
      },
	   // 已有数据...
	  startDate: '', // 开始时间
	  endDate: '',   // 结束时间
	  // 日期选择器配置
	  startDatePickerOptions: {
		disabledDate: (time) => {
		  if (this.endDate) {
			return time.getTime() > new Date(this.endDate).getTime();
		  }
		  return false;
		}
	  },
	  endDatePickerOptions: {
		disabledDate: (time) => {
		  if (this.startDate) {
			return time.getTime() < new Date(this.startDate).getTime();
		  }
		  return false;
		}
	  },
      leftTableData: [],
	  tableData:[],
	  usedFrquIdOptions:[], // 默认给药方式
	  cachedTableData: [], // 用于缓存表格数据
	  // title右侧按钮
	  headerBtn:[
	   { refesh:"refesh", title:"刷新", type:"warning", icon:"el-icon-refresh" },
	   { senior:"senior", title:"高级", type:"success", icon:"" },
	  ],
	  tableRows:[
	  	{ name:"处方类型", prop:"rxName" },
		{ name:"处方科室", prop:"bilgDeptName", type:"" },
	  	{ name:"处方医生", prop:"bilgDrName" },
	  	{ name:"合计金额", prop:"saleAmt" },{ name:"退药金额", prop:"reAmt", type:"" },
	  	{ name:"划价人", prop:"bilgOptName", type:"" },
	  	{ name:"划价时间", prop:"bilgDate" },
	  	{ name:"发药人", prop:"dismedOptName" },{ name:"发药时间", prop:"dismedOptDate", type:"" },
	  	{ name:"收费时间", prop:"costDate", type:"" },
	  ],
	  tableRows2:[],
		// 其他数据...
		refundReasons: [
		  { value: '患者过敏', id: 1 },
		  { value: '药品不良反应', id: 2 },
		  { value: '医生更改处方', id: 3 },
		  { value: '患者病情变化', id: 4 },
		  { value: '药品质量问题', id: 5 },
		  { value: '患者拒绝用药', id: 6 },
		  { value: '用药剂量错误', id: 7 },
		  { value: '药品过期', id: 8 },
		  { value: '药品包装破损', id: 9 },
		  { value: '其他原因', id: 10 }
		],
		statusMap: {
			0: '草稿',
			1: '已收费',
			2: '已配药',
			3: '已发药',
			4: '待退费',
			5: '已退药',
			6: '已作废'
		},
		pricingTypeMap: {
			1: '医嘱划价',
			2: '手工划价',
			3: '互联网划价',
		},
		pricingTypeMapIconMap: {
			1: 'el-icon-top-juhezhifu',
			2: 'el-icon-bzdw',
			3: 'el-icon-bottom-gz',
		},
		statusIconMap: {
			0: 'el-icon-document',
			1: 'el-icon-top-juhezhifu',
			2: 'el-icon-bzdw',
			3: 'el-icon-bottom-gz',
			4: 'el-icon-document-checked',
			5: 'el-icon-document-flxz',
		},
		statusColorMap: {
			0: '#cacaca',
			1: '#E6A23C',
			2: '#E6A23C',
			3: '#409EFF',
			4: '#F56C6C',
			5: '#67C23A'
		},
		TypeMap:{
			1: '数据默认null',
			// ...待接口响应
		},
		selectOption:[{id:1,label:'中药库',value:'中药库'},{id:2,label:'中药库',value:'中药库'},{id:3,label:'中药房',value:'中药房'},{id:4,label:'中药房',value:'中药房'}],//库房
		shedIdMap: {
			1: '中药库',
			2: '中药库',
			3: '中药房',
			4: '中药房',
		},
		addForm: {
			"age": 0,
			"bilgDeptId": 0,
			"bilgDeptName": "",
			"id": 0,
			"name": "",
			"phayId": 0,
			"pricingType": 0,
			"remark": "",
			"rxName": "",
			"rxNo": 0,
			"rxName": 0,
			"saleAmt": 0,
			"sex": 0,
			"refundList":[]
		},
	  refundTotalAmount: 0,
      rightTableData: [],
	  innerTableData: [], // 退药模态框内部表格数据
      closeAfterPrint: true,
	  showDatas: false,
	  filterState: '', // 状态筛选值
	  // 退费相关
	  refundDetailVisible: false,
	  isRefundAllowed: false,    // 退费按钮状态
	  isDrugRefundAllowed: false, // 退药按钮状态
	  isOtherActionAllowed: false, // 其他按钮状态
	  currentOrder: {},
      leftTableHeight: '100%',
      rightTableHeight: '100%'
    }
  },
  mounted() {
	this.loadData();
    this.calculateTableHeights();
    window.addEventListener('resize', this.calculateTableHeights);
	// 页面加载完成后启用所有按钮
	this.buttonsDisabled = false;
	this.getMedication();
	// 设置默认时间为当天范围
	  this.setDefaultDateRange();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calculateTableHeights);
  },
  // computed: {
  //     // 是否允许退费（state为4时允许）
  //     isRefundAllowed() {
  //       return this.currentTable && Number(this.currentTable.state) === 4;
  //     },
      
  //     // 是否允许退药（state为3时允许）
  //     isDrugRefundAllowed() {
  //       return this.currentTable && Number(this.currentTable.state) === 3;
  //     },
      
  //     // 其他按钮是否允许操作（state为0-5时都允许，但优先级低于特定按钮）
  //     isOtherActionAllowed() {
  //       return this.currentTable && 
  //         [0, 1, 2, 3, 4, 5].includes(Number(this.currentTable.state));
  //     }
  //   },
  methods: {
	async loadData() {
	  this.loading = true;
	  
	  // 确保时间参数已设置
	  if (!this.startDate || !this.endDate) {
	    await this.setDefaultDateRange();
	  }
	  
	  // 验证日期范围
	  if (this.startDate && this.endDate) {
	    const start = new Date(this.startDate).getTime();
	    const end = new Date(this.endDate).getTime();
	    if (start > end) {
	      this.$message.warning('开始时间不能晚于结束时间');
	      this.loading = false;
	      return;
	    }
	  }
	  
	  try {
	    let res = await rxmainPage({
	      condis: this.searchValue,
	      startDate: this.startDate,
	      endDate: this.endDate,
	      state: this.filterState,
	      pageNum: this.pageNum,
	      pageSize: this.pageSize,
	    });
	    
	    if(res.code === 200) {
	      this.tableData = res.data.content.map(item => {
	        item.state = Number(item.state);
	        return item;
	      });
	      this.totalSize = res.data.totalSize;
	    } else {
	      this.$message.error(res.message || '获取数据失败');
	      this.tableData = [];
	    }
	  } catch (error) {
	    console.error('加载数据出错:', error);
	    this.$message.error('加载数据失败');
	  } finally {
	    this.loading = false;
	  }
	},
	// 给药方式
	async getMedication(){
		let res = await getMedicationFrequency();
		if(res.code===200){ 
			this.usedFrquIdOptions=res.data
			// 将 给药方式 转换为 politicalMap 格式
			this.TypeMap = this.usedFrquIdOptions.reduce((map, item) => {
				map[item.id] = item.name;  // 使用 id 作为键，label 作为值
				return map;
			}, { 1: '数据不对，默认admin' });  // 保留初始值
			console.log(this.TypeMap,'将 给药方式 转换为 politicalMap 格式');
		}
	},
    calculateTableHeights() {
      // 计算左侧表格高度
      const leftFormHeight = document.querySelector('.left-form')?.offsetHeight || 300;
      const leftTableHeight = window.innerHeight - 50 - 50 - leftFormHeight - 20; // 减去header、bottom和form高度以及padding
      this.leftTableHeight = Math.max(200, leftTableHeight) + 'px';
      
      // 计算右侧表格高度
      const rightFormHeight = document.querySelector('.right-form')?.offsetHeight || 300;
      const rightTableHeight = window.innerHeight - 50 - 50 - rightFormHeight - 20; // 减去header、bottom和form高度以及padding
      this.rightTableHeight = Math.max(200, rightTableHeight) + 'px';
    },
	// 新增查看方法
	handleView() {
	    if (!this.currentTable) {
	      this.$message.warning('请先选择一条处方数据');
	      return;
	    }
	    
	    // 缓存当前数据
	    this.cachedTableData = [...this.tableData];
	    
	    // 打开模态框
	    this.detailDialogVisible = true;
	    this.tableData = [...this.cachedTableData]
	    
	    // 获取药品详情
	    this.loadMedicineDetail(this.currentTable.id);
	  },
		// 辅助方法：获取病人类型
		getPatientType(type) {
		  const types = {
			1: '普通病人',
			2: '慢特病人',
			3: '医保病人',
			4: '自费病人'
		  };
		  return types[type] || '未知类型';
		},
		// 查询条件
		found(){
			this.loadData();
		},
		// 加载药品详情
		async loadMedicineDetail(prescriptionId) {
		  try {
			this.loading = true;
			const res = await getRefundDrug({
				id: this.currentTable.id
			});
			if (res.code === 200) {
			  console.log(res.data,'this.detailMedicineList');
			  this.detailMedicineList = res.data.refundList;
			  this.detailForm = res.data;
			  // map((item, index) => ({
			  // rowNum: index + 1,
			  // code: item.drugCode,
			  // name: item.drugName,
			  // spec: item.specification,
			  // type: item.drugType,
			  // manufacturer: item.manufacturer,
			  // quantity: item.quantity,
			  // unit: item.unit,
			  // price: item.price,
			  // amount: item.amount,
			  // dosage: item.dosage,
			  // dosageUnit: item.dosageUnit
			  // }));
			}
		  } catch (error) {
			console.error('加载药品详情失败:', error);
		  } finally {
			this.loading = false;
		  }
		},
	// 步骤
	handClick(v,i) {
		 // i event
		  // 处理逻辑 => 打印
		if(v.title == '打印' || v.title.includes('打印')){
			if(!this.currentTable || this.currentTable.length === 0){
			  this.$message({ type: 'warning', message: '请先单击选择一条数据'});
			} else if(this.currentTable.state != 5) {
			  this.$message({ type: 'error', message: '只能打印已过单的数据!'});
			} else {
			  this.currentTable.name = '打印'
			  this.$refs.exaRef.openModel(this.currentTable)
			}
		}
		// 处理逻辑 => 页面刷新
		else if(v.title == '刷新' || v.title.includes('刷新')){
			this.loading = true;
			setTimeout(() => {
				this.reload();
				this.$message({type:'success',message:'已刷新'})
				this.loading = false;		
			}, 1500)
		}
		// 处理逻辑 => 高级选项设置
		else if(v.title == '高级选项' || v.title.includes('高级')){
			// this.openSettings();
		}
	},
	
	// 状态筛选变化处理方法
	handleStateFilterChange(val) {
	  this.filterState = val;
	  this.loadData();
	},
	// 新增方法：设置默认日期范围
	setDefaultDateRange() {
	  const now = new Date();
	  
	  // 设置开始时间为当天00:00:00
	  const startDate = new Date(now);
	  startDate.setHours(0, 0, 0, 0);
	  this.startDate = this.formatDate(startDate);
	  
	  // 设置结束时间为当天23:59:59
	  const endDate = new Date(now);
	  endDate.setHours(23, 59, 59, 999);
	  this.endDate = this.formatDate(endDate);
	  
	  // 确保UI更新后返回Promise
	  return this.$nextTick();
	},
	
	formatDate(date) {
	  // 确保传入的是Date对象
	  if (!(date instanceof Date)) {
	    console.error('formatDate: 参数不是Date对象', date);
	    return '';
	  }
	  
	  const year = date.getFullYear();
	  const month = String(date.getMonth() + 1).padStart(2, '0');
	  const day = String(date.getDate()).padStart(2, '0');
	  const hours = String(date.getHours()).padStart(2, '0');
	  const minutes = String(date.getMinutes()).padStart(2, '0');
	  const seconds = String(date.getSeconds()).padStart(2, '0');
	  
	  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	},
	// 修改handleRefundPrice方法
	async handleRefundPrice() {
	    if (!this.currentTable) {
	      this.$message.warning('请先选择一条处方数据');
	      return;
	    }
	    
	    try {
	      this.loading = true;
	      // 缓存当前数据
	      this.cachedTableData = [...this.tableData];
	      
	      const res = await getRefundDrug({
	        id: this.currentTable.id
	      });
	      
	      if (res.code === 200) {
	        this.currentOrder = res.data;
	        this.refundDetailVisible = true;
	      } else {
	        this.$message.error(res.message || '获取订单详情失败');
	      }
	    } catch (error) {
	      console.error('获取订单详情出错:', error);
	      this.$message.error('获取订单详情出错');
	    } finally {
	      this.loading = false;
	    }
	},
	// 确认退费按钮点击事件
	async handleConfirmRefund() {
	  try {
	    this.loading = true;
	    
	    // 1. 验证是否有选中处方和退费数据
	    if (!this.currentTable) {
	      this.$message.warning('请先选择一条处方数据');
	      return;
	    }
	
	    // 2. 获取处方详情数据（确保包含saleAmt）
	    const res = await getRefundDrug({
	      id: this.currentTable.id
	    });
	
	    if (res.code !== 200 || !res.data) {
	      this.$message.error(res.message || '获取处方详情失败');
	      return;
	    }
	
	    // 3. 准备请求参数
	    const params = {
	      id: this.currentTable.id, // 处方ID
	      reAmt: res.data.saleAmt, // 直接从接口响应获取总金额
	      voList: res.data.refundList.map(item => ({
	        id: item.id, // 药品ID
	        retnAmt: item.saleAmt || 0, // 单行退费金额，默认0
	        retnCnt: item.cnt || 0  // 退费数量，默认0
	      }))
	    };
	
	    console.log('退费参数:', params);
	    
	    // 4. 验证voList是否为空
	    if (params.voList.length === 0) {
	      this.$message.error('没有可退费的药品项目');
	      return;
	    }
	    
	    // 5. 调用tyrefund接口
	    const refundRes = await tyrefund(params);
	    
	    if (refundRes.code === 200) {
	      this.$message.success('退费成功');
		  this.loading=false;
	      this.refundDialogVisible = false;
	      this.loadData(); // 刷新数据
	    } else {
			this.loading=false;
	      this.$message.error(refundRes.message || '退费失败');
	    }
	  } catch (error) {
	    console.error('退费出错:', error);
	    this.$message.error('退费操作出错');
	  } finally {
	    this.loading = false;
	  }
	},
	// 修改原有的handleCurrentTableChange方法
	handleCurrentTableChange(val) {
	  this.currentTable = val ? {...val} : null;
	  
	  // 重置所有按钮状态
	  this.isRefundAllowed = false;
	  this.isDrugRefundAllowed = false;
	  this.isOtherActionAllowed = false;
	
	  if (val) {
	    const state = Number(val.state);
	    const statusName = this.statusMap[state] || '未知状态';
	    
	    // 根据状态设置按钮可用性
		if (state === 1) {
		  this.isRefundAllowed = true; // 启用退费按钮
		  this.isOtherActionAllowed = true; // 启用其他按钮
		  this.$message.success(`当前处方状态为"${statusName}"，只有【已发药】状态或【已退药】状态的处方才能进行退药操作!`);
		}
	    else if (state === 3) {
	      this.isDrugRefundAllowed = true; // 启用退药按钮
	      this.isOtherActionAllowed = true; // 启用其他按钮
	      // this.$message.success(`当前处方状态为"${statusName}"，允许退药操作`);
	    } else if (state === 4) {
	      this.isRefundAllowed = true; // 启用退费按钮
	      this.isOtherActionAllowed = true; // 启用其他按钮
	      // this.$message.success(`当前处方状态为"${statusName}"，允许退费操作`);
	    } else {
	      this.isOtherActionAllowed = [0, 1, 2, 5].includes(state); // 其他状态只允许基本操作
	      // this.$message.info(`当前处方状态为"${statusName}"，退药/退费操作不可用`);
	    }
	  }
	},
	
	// 其他方法中涉及tableData的也需要修改为innerTableData
	handleSelectionChange(rows) {
	  this.selectedRows = rows;
	  // 自动计算总金额
	  this.calculateRefundTotal();
	},
	handleRowClick(row) {
	  // 点击行时自动选中/取消选中
	  this.$refs.innerTable.toggleRowSelection(row);
	},
	resetDates() {
	    this.startDate = '';
	    this.endDate = '';
	  },
	  
	// 开始编辑行
	startEdit(row) {
	  // 保存原始值用于恢复
	  if (!row._originalRetnCnt) {
	    row._originalRetnCnt = row.retnCnt;
	  }
	  this.$set(row, 'editing', true);
	},
	// 确认编辑
	confirmEdit(row) {
	  // 验证输入值
	  if (!/^[1-9]\d*$/.test(row.retnCnt)) {
	    this.$message.error('待退数量必须为正整数');
	    row.retnCnt = row._originalRetnCnt || 0;
	    return;
	  }
	  
	  if (row.retnCnt > row.quantity) {
	    this.$message.error('待退数量不能超过可退数量');
	    row.retnCnt = row._originalRetnCnt || 0;
	    return;
	  }
	  
	  // 计算退药金额
	  this.calculateRowAmount(row);
	  
	  // 退出编辑状态
	  this.$set(row, 'editing', false);
	  delete row._originalRetnCnt;
	  
	  // 调用测试接口A
	  this.callTestApiA(row);
	},

	// 添加删除方法
	async handleDelete() {
	  // 检查是否选中了行数据
	  if (!this.currentTable) {
	    this.$message.warning('请先单击选择一条处方数据');
	    return;
	  }
	
	  try {
	    // 确认删除对话框
	    await this.$confirm('确定要删除这条退药数据吗?', '提示', {
	      confirmButtonText: '确定',
	      cancelButtonText: '取消',
	      type: 'warning'
	    });
	
	    this.loading = true;
	    
	    // 调用删除接口
	    const res = await deltyrefund({
	      id: this.currentTable.id // 使用当前选中行的id作为参数
	    });
	
	    if (res.code === 200) {
	      this.$message.success('删除成功');
	      this.loadData(); // 刷新数据
	    } else {
	      this.$message.error(res.message || '删除失败');
	    }
	  } catch (error) {
	    if (error !== 'cancel') {
	      console.error('删除出错:', error);
	      this.$message.error('删除操作出错');
	    }
	  } finally {
	    this.loading = false;
	  }
	},
	
	 // 打开退药模态框
	   openRefundDialog(data) {
	     if (data) {
	       this.addForm = { ...this.addForm, ...data };
	     }
	     this.refundDialogVisible = true;
	     this.calculateRefundTotal();
	   },
	    
	    // 关闭退药模态框
	    // 修改handleCloseRefundDialog方法
	      handleCloseRefundDialog() {
	        this.$confirm('确定要关闭退药窗口吗？', '提示', {
	          confirmButtonText: '确定',
	          cancelButtonText: '取消',
	          type: 'warning'
	        }).then(() => {
	          this.refundDialogVisible = false;
	          // 恢复缓存数据
	          // this.tableData = [...this.cachedTableData];
	          // this.resetForm();
	        }).catch(() => {});
	      },
		// 计算单行金额
		calculateRowAmount(row) {
		  // 确保retnCnt是数字类型
		  const retnCnt = Number(row.retnCnt) || 0;
		  const retnAmt = Number(row.minSalePric) || 0;
		  
		  // 计算待退金额
		  row.retnAmt = (retnCnt * minSalePric).toFixed(2);
		  
		  // 更新总金额
		  this.calculateRefundTotal();
		},
		// 金额格式化方法
		formatCurrency(value) {
		  if (isNaN(value)) return '0.00';
		  return Number(value).toLocaleString('zh-CN', {
		    minimumFractionDigits: 2,
		    maximumFractionDigits: 2
		  });
		},
		// 调用测试接口A  , 单个退药
		// async callTestApiA(row) {
		// 	console.log(row,'单个退药单个退药单个退药');
		//   try {
		//     this.loading = true;
		//     // 准备请求参数
		// 	let abc = [];
			
		//     const params = {
		// 		id: row.id,
		// 		retnAmt: row.retnAmt,
		// 		// "reAmt": 0,
		// 		retnCnt: row.retnCnt
		//     };
		//     console.log(abc,'单个退药数据数据单个退药数据数据单个退药数据数据单个退药数据数据单个退药数据数据单个退药数据数据单个退药数据数据单个退药数据数据');
		// 	abc.push(params)
		//     // 这里替换为实际的测试接口A调用
		//     const res = await tySave(abc);
		    
		//     if (res.code === 200) {
		//       this.$message.success('退药操作成功');
		//       // 可以在这里更新表格数据
		//     } else {
		//       this.$message.error(res.message || '退药操作失败');
		//     }
		//   } catch (error) {
		//     console.error('调用接口出错:', error);
		//     this.$message.error('退药操作出错');
		//   } finally {
		//     this.loading = false;
		//   }
		// },
		
		async handleBatchRefund() {
		  try {
		    this.loading = true;
		    
		    // 1. 检查是否有有效待退数量的行
		    if (this.selectedRows.length === 0) {
		      this.$message.warning('请至少设置一条有效的待退数量');
		      return;
		    }
		    
		    // 2. 准备请求参数
		    const params = {
		      id: this.addForm.id, // 处方ID
		      reAmt: this.refundTotalAmount, // 总退药金额
		      voList: this.selectedRows.map(row => ({
		        id: row.id, // 药品ID
		        retnAmt: row.retnAmt, // 退药金额
		        retnCnt: row.retnCnt // 退药数量
		      })),
		      refundReason: this.addForm.refundReason // 退药原因
		    };
		    
		    // 3. 调用API
		    const res = await tySave(params);
		    
		    if (res.code === 200) {
		      this.$message.success('退药成功');
		      this.refundDialogVisible = false;
		      this.loadData(); // 刷新数据
		    } else {
		      this.$message.error(res.message || '退药失败');
		    }
		  } catch (error) {
		    console.error('退药出错:', error);
		    this.$message.error('退药操作出错');
		  } finally {
		    this.loading = false;
		  }
		},
		    
		    // 处理关闭退费详情弹窗
		    handleCloseRefundDetail() {
		      this.refundDetailVisible = false
		      this.currentOrder = {}
		    },
		    
		    // 处理确认退款
		    // 修改confirmRefund方法
		    async confirmRefund() {
		      // if (!this.addForm.refundReason) {
		      //   this.$message.warning('请填写退药原因');
		      //   return;
		      // }
		      // 检查退药原因
			if (!this.addForm.refundReason || this.addForm.refundReason.trim() === '') {
			  this.$message.warning('请填写或选择退药原因');
			  return;
			}
		      // 检查是否有待退药品
		      const hasRefundItems = this.tableData.some(item => item.retnCnt > 0);
		      if (!hasRefundItems) {
		        this.$message.warning('请至少选择一种药品并设置待退数量');
		        return;
		      }
		      
		      try {
		        this.loading = true;
		        
		        // 准备退药数据，按照要求的格式
		        const params = {
		          id: this.addForm.id, // 处方ID
		          reAmt: this.refundTotalAmount, // 总退药金额
		          voList: this.tableData
		            .filter(item => item.retnCnt > 0)
		            .map(item => ({
		              id: item.id, // 药品ID
		              retnAmt: item.retnAmt, // 单行退药金额
		              retnCnt: item.retnCnt // 退药数量
		            })),
		          refundReason: this.addForm.refundReason // 退药原因
		        };
		        
		        console.log('退药参数:', params);
		        
		        // 调用tySave接口
		        const res = await tySave(params);
		        
		        if (res.code === 200) {
		          this.$message.success('退药成功');
		          this.refundDialogVisible = false;
		          this.resetForm();
		          this.loadData(); // 刷新表格数据
		        } else {
		          this.$message.error(res.message || '退药失败');
		        }
		      } catch (error) {
		        console.error('退药出错:', error);
		        this.$message.error('退药出错');
		      } finally {
		        this.loading = false;
		      }
		    },
	   
		// 处理退药按钮点击 =>  在 handleRefund 方法中确保正确赋值 再次验证，防止通过其他方式触发
		// 在打开退药模态框时初始化数据
		  async handleRefund() {
		    if (!this.currentTable) {
		      this.$message.warning('请先选中一条处方数据');
		      return;
		    }
		    
		    try {
		      this.loading = true;
		      this.editingIndex = -1; // 重置编辑状态
		      
		      const res = await getRefundDrug({
		        id: this.currentTable.id
		      });
		      
		      if (res.code === 200) {
		        this.innerTableData = res.data.refundList.map(item => ({
		          ...item,
		          retnCnt: 0, // 初始待退数量为0
		          retnAmt: 0  // 初始待退金额为0
		        }));
		        
		        this.refundTotalAmount = 0; // 初始总退药金额为0
		        this.addForm = {
		          ...res.data,
		          // saleAmt: 0 // 初始总退药金额为0
		        };
		        
		        this.refundDialogVisible = true;
		      }
		    } catch (error) {
		      console.error('退药详情获取失败:', error);
		    } finally {
		      this.loading = false;
		    }
		  },
		
		// 处理单元格双击事件
		  handleCellDblClick(row, index) {
		    this.editingIndex = index;
		    this.$nextTick(() => {
		      this.$refs.editInput && this.$refs.editInput.focus();
		    });
		  },
		// 处理单元格单击事件
		  handleCellClick(row, index) {
		    this.editingIndex = index;
		    this.$nextTick(() => {
		      this.$refs.editInput && this.$refs.editInput.focus();
		    });
		  },
		  
		handleEditBlur(row, index) {
		  // 验证输入值
		  if (row.retnCnt === null || row.retnCnt === '' || isNaN(row.retnCnt)) {
		    this.$message.error('待退数量必须为数字且不能为空');
		    row.retnCnt = 0;
		    row.retnAmt = 0;
		    this.editingIndex = -1;
		    this.removeFromSelectedRows(row);
		    return;
		  }
		  
		  row.retnCnt = Number(row.retnCnt);
		  
		  // 验证是否为大于0的正整数
		  if (!Number.isInteger(row.retnCnt) || row.retnCnt <= 0) {
		    this.$message.error('待退数量必须为大于0的正整数');
		    row.retnCnt = 0;
		    row.retnAmt = 0;
		    this.editingIndex = -1;
		    this.removeFromSelectedRows(row);
		    return;
		  }
		  
		  // 验证不能超过可退数量
		  if (row.retnCnt > row.cnt) {
		    this.$message.error('待退数量不能超过可退数量');
		    row.retnCnt = row.cnt;
		    this.editingIndex = -1;
		  }
		  
		  // 计算当前行的退药金额
		  row.retnAmt = (row.retnCnt * row.minSalePric).toFixed(2);
		  
		  // 确保行数据有id属性
		  if (!row.id) {
		    console.error('行数据缺少id属性:', row);
		    this.$message.error('数据错误，缺少药品ID');
		    return;
		  }
		  
		  // 添加或更新到selectedRows
		  this.addOrUpdateSelectedRow(row);
		  
		  // 计算总退药金额
		  this.calculateRefundTotal();
		  
		  // 退出编辑状态
		  this.editingIndex = -1;
		},
		
		// 添加或更新选中行
		addOrUpdateSelectedRow(row) {
		  const index = this.selectedRows.findIndex(item => item.id === row.id);
		  if (index === -1) {
		    // 添加新行
		    this.selectedRows.push({
		      id: row.id,
		      retnCnt: row.retnCnt,
		      retnAmt: row.retnAmt,
		      // 其他必要字段...
		      ...row
		    });
		  } else {
		    // 更新已有行
		    this.selectedRows.splice(index, 1, {
		      ...this.selectedRows[index],
		      retnCnt: row.retnCnt,
		      retnAmt: row.retnAmt
		    });
		  }
		},
		
		// 更新选中行和总金额
		updateSelectedRows() {
		  // 筛选出有效的行
		  this.selectedRows = this.innerTableData.filter(row => 
		    row.retnCnt > 0 && row.retnCnt <= row.cnt
		  );
		  
		  // 计算总退药金额
		  this.calculateRefundTotal();
		},
		
		// 添加到选中行
		addToSelectedRows(row) {
		  if (!this.selectedRows.some(item => item.id === row.id)) {
		    this.selectedRows.push(row);
		  }
		},
		
		// 从选中行中移除
		removeFromSelectedRows(row) {
		  this.selectedRows = this.selectedRows.filter(item => item.id !== row.id);
		},
		
		// 计算单行退药金额
		calculateRefundAmount(row) {
		  row.retnAmt = (row.retnCnt * row.minPurcPric).toFixed(2);
		  this.calculateRefundTotal();
		},

		calculateRefundTotal() {
		  // 计算所有行的待退金额总和
		  this.refundTotalAmount = this.innerTableData.reduce((total, row) => {
		    return total + (Number(row.retnAmt) || 0);
		  }, 0);
		  
		  // 更新表单中的总金额
		  this.addForm.saleAmt = this.refundTotalAmount;
		},
		
	    
	    // 清空所有退药数量
	    clearAll() {
	      this.innerTableData.forEach(row => {
	        row.retnCnt = 0;
	        row.retnAmt = 0;
	      });
	      this.selectedRows = [];
	      this.refundTotalAmount = 0;
	      this.addForm.saleAmt = 0;
	    },
	    
	    // 全退按钮点击事件
	    async refundAll() {
	      try {
	        this.loading = true;
	        
	        // 1. 设置所有行的retnCnt为最大可退数量
	        this.innerTableData.forEach(row => {
	          row.retnCnt = row.cnt;
	          row.retnAmt = (row.retnCnt * row.minSalePric).toFixed(2);
	        });
	        
	        // 2. 更新selectedRows
	        this.selectedRows = this.innerTableData.map(row => ({
	          id: row.id,
	          retnCnt: row.retnCnt,
	          retnAmt: row.retnAmt,
	          ...row
	        }));
	        
	        // 3. 重新计算总金额
	        this.calculateRefundTotal();
	        
	        // 4. 准备请求参数
	        const params = {
	          id: this.addForm.id,
	          reAmt: this.refundTotalAmount,
	          voList: this.selectedRows.map(row => ({
	            id: row.id,
	            retnAmt: row.retnAmt,
	            retnCnt: row.retnCnt
	          })),
	          refundReason: '全部退药'
	        };
	        
	        // 5. 调用API
	        const res = await tySave(params);
	        
	        if (res.code === 200) {
	          this.$message.success('全部退药成功');
	          this.refundDialogVisible = false;
	          this.loadData();
	        } else {
	          this.$message.error(res.message || '全部退药失败');
	        }
	      } catch (error) {
	        console.error('全部退药出错:', error);
	        this.$message.error('全部退药操作出错');
	      } finally {
	        this.loading = false;
	      }
	    },
		  
	    getRowClass({row}) {
	        return `state-${row.state}`;
	      },
	    // 确认退药
	  //   async confirmRefund() {
	  //     if (!this.addForm.refundReason) {
	  //       this.$message.warning('请填写退药原因');
	  //       return;
	  //     }
	      
	  //     // 检查是否有待退药品
	  //     const hasRefundItems = this.tableData.some(item => item.retnCnt > 0);
	  //     if (!hasRefundItems) {
	  //       this.$message.warning('请至少选择一种药品并设置待退数量');
	  //       return;
	  //     }
	      
	  //     try {
	  //       this.loading = true;
	        
	  //       // 准备退药数据
	  //       this.addForm.refundList = this.tableData
			
			//   // .filter(item => item.retnCnt > 0)
			//   // .map(item => ({
			//   //   drugId: item.drugId,
			//   //   drugCode: item.drugCode,
			//   //   drugName: item.drugName,
			//   //   drugSpec: item.drugSpec,
			//   //   retnCnt: item.retnCnt,
			//   //   salePric: item.salePric,
			//   //   retnAmt: item.retnAmt,
			//   //   manuLotnum: item.manuLotnum,
			//   // }));
	  //       // 将退药金额赋值为外层 addForm 的 saleAmt
			// // this.addForm.saleAmt = this.refundTotalAmount;
			// // this.addForm.saleAmt = this.refundTotalAmount;
			// this.addForm.reAmt = this.refundTotalAmount;
			//   console.log(this.addForm,'oooooooo');
	  //       // 调用退药API
	  //       const res = await tySave(this.addForm);
	  //       if (res.code === 200) {
	  //         this.$message.success('退药成功');
	  //         this.refundDialogVisible = false;
	  //         this.resetForm();
	  //         this.loadData(); // 刷新表格数据
	  //       } else {
	  //         this.$message.error(res.message || '退药失败');
	  //       }
	  //     } catch (error) {
	  //       this.$message.error('退药出错: ' + error.message);
	  //     } finally {
	  //       this.loading = false;
	  //     }
	  //   },
	    
	    // 提交退药
	    submitRefund() {
	      const refundItems = this.refundDrugList
	        .filter(item => item.toRefundQty > 0)
	        .map(item => ({
	          drugCode: item.drugCode,
	          drugName: item.drugName,
	          quantity: item.toRefundQty,
	          amount: item.toRefundAmount
	        }));
	      
	      const params = {
	        ...this.addForm,
	        refundItems,
	        refundAmount: this.refundTotalAmount
	      };
	      
	      // 这里调用实际的退药API
	      console.log('退药参数:', params);
	      // api.submitRefund(params).then(res => {...})
	      
	      this.$message.success('退药成功');
	      this.refundDialogVisible = false;
	      this.resetForm();
	    },
	    
	    // 重置表单
	    resetForm() {
	      this.refundDrugList.forEach(item => {
	        item.toRefundQty = 0;
	        item.toRefundAmount = 0;
	      });
	      this.refundTotalAmount = 0;
	      this.addForm.remark = '';
	      this.addForm.refundReason = '';
	  },
	  // 打印处方
	  gotoPrint(){
		console.log('打印处方');
	  },
	// 添加多选变化事件
	// handleSelectionChange(val) {
	//   this.multipleSelection = val;
	//   // 判断是否全选
	//   this.isAllSelected = val.length > 0 && val.length === this.tableData.length;
	  
	//   // 如果有选中项，设置当前行为第一个选中项
	//   if (val.length > 0) {
	//     this.$nextTick(() => {
	//       this.$refs.table.setCurrentRow(val[0]);
	//     });
	//   } else {
	//     this.$refs.table.setCurrentRow(null);
	//   }
	  
	//   this.updateButtonStates();
	// },
	// col 里面包含了表头字段和名称，list 是表格数据
	columnWidth(col, list) {
		let prop = col.prop,lab = col.lab;
		let width = 40; // 设定一个最小值
		let maxlenStr = ""; // 最长字符串
		for (let info of list) {
	       if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
	    }
	    width = Math.max(width, len(lab), len(maxlenStr));
	    // 表格自带的内边距(20px) 自调
	    return width + 12; // 这里加了 12px
	    function len(str) {
	       // 实际分配长度可根据需要自行调整
	       let length = 8;
	       for (const char of str + "") {
	         // 英文小写字符 8px
	         if ("a" <= char && char <= "z") length += 8;
	         // 英文大写字符 8px
	         else if ("A" <= char && char <= "Z") length += 8;
	         // 中文字符 28px
	         else if (char >= "\u4e00" && char <= "\u9fa5") length += 32;
	         // 其他 8px
	         else length += 12;
	       }
	       return length;
	    }
	},
	// 打开最小化未保存清空的表单
	restoreDialog() {
		this.addDialogVisible = true;
		this.isMinimized = false;
	},
	// 关闭详情模态框
	handleCloseDetailDialog(done) {
	    // 恢复缓存数据
	    this.tableData = [...this.cachedTableData];
	    done();
	},
	//分页
	//每页条数改变触发
	handleSizeChange(val) {
		console.log(`每页 ${val} 条`);
		this.pageNum = val;
		this.loadData();
	},
	//当前条数改变触发
	handleCurrentChange(val) {
		console.log(`当前页: ${val}`);
		this.pageNum = val;
		this.loadData();
	},
	
  }
}
</script>

<style lang="less" scoped>
	.datePicker {
	  display: flex;
	  align-items: center;
	  margin-left: 20px;
	  
	  .el-date-editor {
	    margin-right: 10px;
	    
	    /deep/ .el-input__inner {
	      height: 28px;
	      line-height: 28px;
	    }
	    
	    /deep/ .el-input__icon {
	      line-height: 28px;
	    }
	  }
	}
	.filter-section {
	  display: flex;
	  align-items: center;
	  margin-left: 20px;
	  
	  .el-select {
	    margin-right: 10px;
	    
	    /deep/ .el-input__inner {
	      height: 28px;
	      line-height: 28px;
	    }
	  }
	}
	/deep/ .el-table .state-3 {
	  background-color: #f0f9eb; /* 已发药 - 绿色背景 */
	}
	/deep/ .el-table .state-1 {
	  background-color: #f5f5f5; /* 已收费 - 灰色背景 */
	}
	/deep/ .el-table .state-0 {
	  background-color: #f5f5f5; /* 草稿 - 灰色背景 */
	}
	/deep/ .el-table .state-2 {
	  background-color: #fdf6ec; /* 已配药 - 橙色背景 */
	}
	/deep/ .el-table .state-4 {
	  background-color: #fef0f0; /* 已退药 - 红色背景 */
	}
	/* 添加编辑状态的样式 */
	/deep/ .el-table .editing-cell {
	  background-color: #f0f9eb;
	}
	
	/* 添加输入框样式 */
	/deep/ .el-table .el-input__inner {
	  height: 28px;
	  line-height: 28px;
	  text-align: center;
	}
	
	/* 添加可点击单元格的悬停效果 */
	/deep/ .el-table .clickable-cell:hover {
	  background-color: #f5f7fa;
	  cursor: pointer;
	}
	/deep/ .el-descriptions__header{
		margin-bottom: 12px;
	}
.send-medici-container {
  width: 100%;
  height: 90vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  overflow: hidden;
  /deep/ .el-table .cell{
  	font-size: 12px;
  	text-overflow: ellipsis;
  	white-space: nowrap;
  	overflow: hidden;
  }
  /deep/ .el-table th{
  	font-size: 12px;
  	background-color: #f1f1f1;
  	border: none;
  	color: #2d2d2d;
  }
  /deep/ .el-table td.el-table__cell div{
  	font-size: 12px;
  }
  /deep/ .el-dialog__body{
  	padding: 12px;
  }
  /deep/ .el-dialog__header{
  	padding: 4px;
  	background-color: #007bb0;
  }
  /deep/ .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
  	margin-bottom: 12px;
  }
  /deep/ .el-dialog__title{
  	color: #fff;
  	font-size: 12px;
  }
  /deep/ .el-dialog__headerbtn .el-dialog__close{
  	color: #fff;
  }
  /deep/ .el-dialog__headerbtn .el-dialog__close:hover{
  	background-color: brown;
  }
  /deep/ .el-dialog__headerbtn{
	top:10px;
  }
  /* 自定义高亮颜色 */
  // ::v-deep .el-table__body tr.current-row > td {
  //   background-color: #0091d4 !important;
  //   color: #f9f9f9; /* 可选：修改文字颜色 */
  // }
  .send-medici-header {
    height: 50px;
    background-color: #409EFF;
    color: white;
    display: flex;
    align-items: center;
    padding: 0 20px;
    flex-shrink: 0;
    
    h4 {
      margin: 0;
      font-size: 16px;
      font-weight: normal;
    }
	.main-icon-c{
		display: flex;
		align-items: center;
		margin-left: 28px;
		/deep/ [data-v-2bacc09b] .el-color-picker__icon, .el-input[data-v-2bacc09b], .el-textarea[data-v-2bacc09b]{
			width: 80%;
		}
	}
  }
  
  .send-medici-main {
    flex: 1;
    display: flex;
    overflow: hidden;
      // table
	  .table{
		width: 100%;
		/deep/ .el-table{
			width: 100%;
			height: 100%;
		}
	  
      /deep/ .el-table .cell{
      	font-size: 12px;
      	text-align: center;
      }
      
      /deep/ .el-table td.el-table__cell div :first-child{
      	text-align: center;
      }
      /deep/ .el-table td.el-table__cell div{
      	text-align: center;
      	overflow: hidden;
      	white-space: normal;
      	word-break: break-all;
      }
	}
  }
  
  .send-medici-bottom {
    height: 50px;
    background-color: white;
    border-top: 1px solid #e6e6e6;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    flex-shrink: 0;
    
    .bottom-left, .bottom-right {
      display: flex;
      align-items: center;
    }
  }
  .refund-dialog {
    .info-section {
      padding: 10px;
      background-color: #f5f7fa;
      border-radius: 4px;
      /deep/ .el-descriptions-item__container{
		  display: flex;
		  align-items: center;
	  }
      .info-item {
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        
        .info-label {
          color: #606266;
          width: 88px;
          text-align: right;
        }
        
        .info-value {
          flex: 1;
          color: #303133;
		  font-size: 12px;
        }
      }
    }
    /* 添加下拉框样式 */
    .send-medici-container /deep/ .el-select {
      width: 100%;
    }
    
    .send-medici-container /deep/ .el-select-dropdown__item {
      font-size: 12px;
      padding: 0 10px;
      height: 28px;
      line-height: 28px;
    }
    
    .send-medici-container /deep/ .el-select .el-input__inner {
      height: 26px;
      line-height: 26px;
    }
    .drug-table {
      ::v-deep .el-table__body-wrapper {
        max-height: 300px;
        overflow-y: auto;
      }
    }
    
    .footer-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 15px;
      padding-top: 15px;
      border-top: 1px solid #ebeef5;
      
      .total-amount {
        .amount-label {
          font-size: 14px;
          color: #606266;
        }
        
        .amount-value {
          font-size: 18px;
          color: #f56c6c;
          font-weight: bold;
        }
      }
      
      .action-buttons {
		text-align: right;
        button {
          margin-left: 10px;
        }
      }
	  
    }
	
  }
}
/* 详情模态框样式 */
.detail-dialog {
  .el-dialog__body {
    // padding: 8px;
    max-height: 80vh;
    overflow-y: auto;
  }
  
 /* 添加表单美化样式 */
 /* 添加Descriptions美化样式 */
 .form-card {
   margin-bottom: 15px;
   border-radius: 6px;
   border: 1px solid #ebeef5;
   background-color: #fff;
   
   .form-descriptions {
     padding: 10px;
     
     /deep/ .el-descriptions__title {
       font-size: 16px;
       font-weight: 600;
       color: #303133;
       margin-bottom: 15px;
       padding-left: 10px;
       position: relative;
       
       &::before {
         content: '';
         position: absolute;
         left: 0;
         top: 50%;
         transform: translateY(-50%);
         width: 4px;
         height: 16px;
         background-color: #409EFF;
         border-radius: 2px;
       }
     }
     
     /deep/ .el-descriptions__body {
       background-color: transparent;
       
       .el-descriptions-item__cell {
         padding: 8px 10px;
       }
       
       .el-descriptions-item__label {
         font-weight: 500;
         color: #606266;
         background-color: #f5f7fa;
       }
       
       .el-descriptions-item__content {
         .el-tag {
           width: 100%;
           text-align: center;
           border: none;
           background-color: #f5f7fa;
           color: #606266;
           
           &.el-tag--info {
             background-color: #f4f4f5;
             color: #909399;
           }
           
           &.el-tag--warning {
             background-color: #fdf6ec;
             color: #e6a23c;
           }
           
           &.el-tag--danger {
             background-color: #fef0f0;
             color: #f56c6c;
             font-weight: bold;
           }
         }
       }
	}
	}
}
 
 .red-text {
   /deep/ .el-input__inner {
     color: #F56C6C;
     font-weight: bold;
   }
 }
  
  .table-card {
    // border-top: 3px solid #67C23A;
  }
  
  .prescription-table {
    margin-bottom: 10px;
  }
  
  .action-buttons {
    // margin-top: 10px;
    text-align: left;
  }
  
  .red-text {
    color: #F56C6C;
    font-weight: bold;
  }
  
  .el-form-item {
    margin-bottom: 4px;
  }
  
  .el-form-item span {
    display: inline-block;
    padding: 0 10px;
    color: #606266;
  }
  }
</style>